package juc.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author fangbin
 * @desc 自旋锁
 *
 * @date 2020/6/12 7:06
 */
public class SpinLock {

    private AtomicReference<Thread> sign = new AtomicReference<>();
    public void lock(){
        Thread current = Thread.currentThread();
        while (!sign.compareAndSet(null,current)){
            //System.out.println(Thread.currentThread().getName()+"我在等待");
        }
    }

    public void unLock(){
        Thread current = Thread.currentThread();
        sign.compareAndSet(current,null);
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"开始尝试获取锁");
                spinLock.lock();
                System.out.println(Thread.currentThread().getName()+"获取得到锁");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                spinLock.unLock();
                System.out.println(Thread.currentThread().getName()+"开始释放锁");
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"开始尝试获取锁");
                spinLock.lock();
                System.out.println(Thread.currentThread().getName()+"获取得到锁");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                spinLock.unLock();
                System.out.println(Thread.currentThread().getName()+"开始释放锁");
            }
        }).start();

    }

}
